package com.example.demo.controller;

import com.example.demo.bean.Building;
import com.example.demo.bean.Product;
import com.example.demo.bean.ResBody;
import com.example.demo.service.ProductService;
import com.example.demo.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
public class ProductController {
    @Autowired
    ProductService service;

//    @RequestMapping("/product")
//    public String product(){
//        return StringUtil.path;
//    }



    @GetMapping("/api/getAllProducts")
    public ResBody getAllProducts(@RequestParam int page,
                                  @RequestParam int limit){
        ResBody resBody = new ResBody();
        int count = service.getCount();
        List<Product> list= service.getAllProducts(page, limit);
        resBody.setCount(count);
        resBody.setData(list);
        resBody.setCode(0);
        return resBody;
    }

    @PostMapping("/api/addProduct")
    public ResBody addProduct(@RequestBody Product product) {
        ResBody resBody = new ResBody();
        int i = service.addProduct(product);
        if (i == 1){
            resBody.setCode(200);
            resBody.setMsg("添加成功");
        }else{
            resBody.setCode(500);
            resBody.setMsg("添加失败");
        }
        return resBody;
    }

    @PostMapping("/api/updateProduct")
    public ResBody updateProduct(@RequestBody Product product) {
        ResBody resBody = new ResBody();
        int i = service.updateProduct(product);
        if (i == 1){
            resBody.setCode(200);
            resBody.setMsg("修改成功");
        }else{
            resBody.setCode(500);
            resBody.setMsg("修改失败");
        }
        return resBody;
    }


    @GetMapping("/api/delProduct")
    public ResBody delProduct(@RequestParam int id) {
        ResBody resBody = new ResBody();
        int i = service.delProduct(id);
        if (i == 1){
            resBody.setCode(200);
            resBody.setMsg("删除成功");
        }else{
            resBody.setCode(500);
            resBody.setMsg("删除失败");
        }
        return resBody;
    }

    @GetMapping("/api/findProductByName")
    public ResBody findProduct(@RequestParam int page,
                                @RequestParam int limit,
                                @RequestParam String name) {
        ResBody resBody = new ResBody();
        int count = service.getCount(name);
        List<Product> list= service.findProductByName(page, limit, name);
        resBody.setCount(count);
        resBody.setData(list);
        resBody.setCode(0);
        return resBody;
    }

    @GetMapping("/ajax/getAllProducts")
    public ResBody getAllProducts() {
        ResBody resBody = new ResBody();
        List<Product> list = service.getAllProducts();
        resBody.setData(list);
        resBody.setCode(0);
        return resBody;
    }


}
